package _9algorithm;

import cn.hutool.core.util.StrUtil;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.security.SecureRandom;
import java.util.Base64;

/**
 * @description: AES非对称加解密算法练习
 * @author: wang zhen
 * @create: 2022-08-03 16:11
 */
public class _1_AESalgorithm {

    private static final String ALGORITHM_NAME = "AES";

    //加密因子，可根据您的需要自定义
    private static final String DEFAULT_ENCRYPT_RULE = "cliSoftonlineshop";
    private static final String RANDOM_KEY_ALGORITHM = "SHA1PRNG";
    private static final String RANDOM_KEY_ALGORITHM_PROVIDER = "SUN";

    public static void main(String[] args){

        long t1 = System.currentTimeMillis();
        String hello = _1_AESalgorithm.encrypt("hello");
        long t2 = System.currentTimeMillis();
        System.out.println("加密耗时:"+(t2-t1)+",密文:"+hello);

        long t3 = System.currentTimeMillis();
        String decrypt = _1_AESalgorithm.decrypt("2342353223");
        long t4 = System.currentTimeMillis();
        System.out.println("解密耗时:"+(t4-t3)+",原文:"+decrypt);
    }

    /**
     * AES加密
     * @param content 待加密的内容，为空时为回空
     * @return 加密后的base64格式的结果，出现异常时返回null
     */
    public static String encrypt(String content) {
        if (StrUtil.isEmpty(content)) {
            return null;
        }
        try {

            //1.创建AES算法生成器、随机数生成器
            KeyGenerator keyGenerator = KeyGenerator.getInstance(ALGORITHM_NAME);//创建密匙生成器
            SecureRandom secureRandom = SecureRandom.getInstance(RANDOM_KEY_ALGORITHM, RANDOM_KEY_ALGORITHM_PROVIDER);//创建保护随机数生成器
            secureRandom.setSeed(DEFAULT_ENCRYPT_RULE.getBytes());//输入密匙

            //2.生成随机数
            keyGenerator.init(128, secureRandom);//初始化128位随机数
            SecretKey originalKey = keyGenerator.generateKey();//生成随机数
            SecretKey secretKey = new SecretKeySpec(originalKey.getEncoded(), ALGORITHM_NAME);
            Cipher cipher = Cipher.getInstance(ALGORITHM_NAME);
            cipher.init(Cipher.ENCRYPT_MODE, secretKey);
            byte[] encrypted = cipher.doFinal(content.getBytes("utf-8"));

            //3.随机数转码为base64
            String result = new String(Base64.getEncoder().encodeToString(encrypted));
            return  result;

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


    /**
     * 解密
     * @param encrypted 加密后的base64格式的密文
     * @return 解密后的原文，出现异常时返回null
     */
    public static String decrypt(String encrypted) {
        if (StrUtil.isEmpty(encrypted)) {
            return null;
        }

        try {

            //1.创建AES算法生成器、随机数生成器
            KeyGenerator keyGenerator = KeyGenerator.getInstance(ALGORITHM_NAME);
            SecureRandom secureRandom = SecureRandom.getInstance(RANDOM_KEY_ALGORITHM, RANDOM_KEY_ALGORITHM_PROVIDER);
            secureRandom.setSeed(DEFAULT_ENCRYPT_RULE.getBytes());

            //2.生成随机数
            keyGenerator.init(128, secureRandom);
            SecretKey originalKey = keyGenerator.generateKey();
            SecretKey secretKey = new SecretKeySpec(originalKey.getEncoded(), ALGORITHM_NAME);
            Cipher cipher = Cipher.getInstance(ALGORITHM_NAME);
            cipher.init(Cipher.DECRYPT_MODE, secretKey);

            //3.随机数解码
            byte[] decrypted = cipher.doFinal(Base64.getDecoder().decode(encrypted));
            return new String(decrypted, "utf-8");

        } catch (Exception e) {
            //e.printStackTrace();
            return null;
        }
    }
}
